import { stringify } from 'querystring';
import { history, Reducer, Effect } from 'umi';

import { fakeAccountLogin } from '@/services/login';
import { setAuthority } from '@/utils/authority';
import { getPageQuery, encryption } from '@/utils/utils';
import {PASSWORD_KEY, AUTH_INFO, ACCESS_TOKEN, CURRENT_MEMBER} from '@/common/constant';
import {setStore} from "@/utils/store";
import {queryCurrent} from "@/services/user";

export interface StateType {
  status?: 'ok' | 'error';
  type?: string;
  currentAuthority?: 'user' | 'guest' | 'admin';
}

export interface LoginModelType {
  namespace: string;
  state: StateType;
  effects: {
    login: Effect;
    logout: Effect;
  };
  reducers: {
    changeLoginStatus: Reducer<StateType>;
  };
}

const Model: LoginModelType = {
  namespace: 'login',

  state: {
    status: undefined,
  },

  effects: {
    *login({ payload }, { call, put }) {
      const user = encryption({
        data: payload,
        key: PASSWORD_KEY,
        param: ['password']
      })
      const response = yield call(fakeAccountLogin, user);
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
      // Login successfully
      if (response['access_token'] && response['access_token'] !== '') {
        // 设置token
        localStorage.setItem(ACCESS_TOKEN, response['access_token']);
        history.replace({
          pathname: '/'
        });
      } else {
        window.location.href = '/';
        return;
      }
    },

    logout() {
      const { redirect } = getPageQuery();
      // Note: There may be security issues, please note
      if (window.location.pathname !== '/user/login' && !redirect) {
        history.replace({
          pathname: '/user/login',
          search: stringify({
            redirect: window.location.href,
          }),
        });
      }
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      setStore({
        name: AUTH_INFO,
        content: payload,
        type: false
      });
      queryCurrent().then(response => {
        setStore({
          name: CURRENT_MEMBER,
          content: response,
          type: false
        });
      });
      setAuthority(payload.username);
      return {
        ...state,
        status: payload.status,
        type: payload.type,
      };
    },
  },
};

export default Model;
